﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EuroManager.Domain.Simulator.AI;
using EuroManager.Domain.Simulator.Engine;
using EuroManager.Domain.Simulator.Tactics;
using EuroManager.Domain.Simulator.World;

namespace EuroManager.Domain.Simulator
{
    public class GameWorldFactory : IGameWorldFactory
    {
        private TimeSpan totalRealTime;
        private IRandomizer random = new Randomizer();

        public GameWorldFactory(TimeSpan totalRealTime)
        {
            this.totalRealTime = totalRealTime;
        }

        public IGameWorld CreateGameWorld()
        {
            GameWorld world = new GameWorld(totalRealTime);

            ITeamTactics tactics1 = new Tactics442();
            ITeamTactics tactics2 = new Tactics442();
            
            Team team1 = CreateTeam(world, PitchSide.Left);
            Team team2 = CreateTeam(world, PitchSide.Right);
            
            team1.Opponent = team2;
            team2.Opponent = team1;

            AddTeamPlayers(world, team1, tactics1);
            AddTeamPlayers(world, team2, tactics2);

            world.AddTeams(team1, team2);

            return world;
        }

        private Team CreateTeam(GameWorld world, PitchSide side)
        {
            Team team = new Team(side, world.Ball);
            TeamAI ai = new TeamAI(team, random);
            world.AddTimeAware(ai);

            return team;
        }

        private void AddTeamPlayers(GameWorld world, Team team, ITeamTactics tactics)
        {
            for (int i = 0; i < Team.PlayerCount; i++)
            {
                PlayerTactics playerTactics = tactics.GetPlayerTactics(i);
                Vector2D kickOffLocation = playerTactics.CalculateKickOffLocation(world.Pitch, team.Side);

                Player player = new Player(i + 1, team, team.Opponent, playerTactics, world.Pitch, world.Ball, random, kickOffLocation);
                team.AddPlayer(player);
                world.AddTimeAware(player);

                PlayerAI ai = new PlayerAI(player, random);
                world.AddTimeAware(ai);
            }
        }
    }
}
